# -*- coding: UTF-8 -*-

import yaml
import os
import subprocess


def read_yaml(yaml_path):
    try:
        # 打开文件
        with open(yaml_path, "r", encoding="utf-8") as f:
            data = yaml.load(f, Loader=yaml.FullLoader)
            return data
    except:
        return None


if __name__ == '__main__':
    yaml_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.yml")
    config = read_yaml(yaml_path)
    assert config is not None, "config为空"

    # 检查源文件夹状态
    assert "source_dir" in config.keys(), "config未设置源文件夹"
    source_dir = config['source_dir']
    assert os.path.exists(source_dir), "源文件夹不存在"

    # 检查目标文件夹状态，若不存在则创建
    dst_dir = config['dst_dir']
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)

    password = config['password']
    winrar_path = os.path.join(config['winrar_dir'],'WinRAR.exe')

    # 构建一个文件夹队列
    dir_query = [source_dir]
    while len(dir_query)!=0:
        # 弹出队头元素
        dir_path = dir_query.pop(0)
        # 检索文件夹
        for file_names in os.listdir(dir_path):
            # 构造绝对路径
            file_path = os.path.join(dir_path, file_names)
            # 判断是否为rar文件
            if os.path.splitext(file_names)[-1] == '.rar':
                dst_file_path = file_path[len(source_dir)+1:]
                dst_file_path = os.path.join(dst_dir,dst_file_path)
                dst_file_path = os.path.dirname(dst_file_path)
                rar_command = r'''"{}" x -p{} -op{} {} *'''.format(winrar_path,password,dst_file_path,file_path)
                print(rar_command)
                os.system(rar_command)

            if not os.path.isfile(file_path):
                # 若是文件夹添加到队列中
                dir_query.append(file_path)
                dst_dir_path = file_path[len(source_dir) + 1:]
                dst_dir_path = os.path.join(dst_dir, dst_dir_path)
                if not os.path.exists(dst_dir_path):
                    # 如果目标文件夹中不存在该文件夹则创建
                    os.makedirs(dst_dir_path)




